/**
 * Created by fang.cai.liang@aliyun.com on 16/7/31.
 */

var pubsub = {}; // 定义一个对象,拥有 publish, subscribe, unsubscribe 方法

//我们可发布的主题
var topics = {'J_S': "军事", "Z_Z": "政治", "J_J": "经济", "W_H": "文化"};

// 主题和订阅者的关系
var ts = {};

(function (ps){

    // 发布的方法
    ps.publish = function(topic, contents){
        if(topics[topic]){
            // 1. 我们可能需要将 主题和内容存储起来

            // 2. 我们应该通知 所有订阅了该主题的订阅者
            setTimeout(function(){
                var subscriberList = ts[topic];
                if(!subscriberList){
                    subscriberList = [];
                }
                for(var i=0; i<subscriberList.length; i ++){
                    subscriberList[i].action(topic, contents);
                }
            }, 1000);

            return true;
        }else{
            // 发布的主题不合法
            return false;
        }
    };

    // 订阅的方法,
    ps.subscribe = function(userid, topic, func){
        if(topics[topic]){
            var subscriberList = ts[topic];
            if(!subscriberList){
                subscriberList = [];
            }
            var subscriber = {"userid": userid, "action" : func};
            subscriberList.push(subscriber);
            ts[topic] = subscriberList;
            return true;
        }else{
            return false;
        }
    };

    // 取消订阅的方法,
    ps.unsubscribe = function(userid, topic){
        if(topics[topic]){
            var subscriberList = ts[topic];
            if(subscriberList){
                for(var i=0; i<subscriberList.length; i ++){
                    if(userid == subscriberList[i].userid){
                        subscriberList.splice(i, 1);
                    }
                }
                return true;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }

}(pubsub));

function User(userid, ps){
    this.userid = userid;
    this.ps = ps;
}

var user1 = new User(111, pubsub);
user1.ps.subscribe(user1.userid, "J_S", function(topic, contents){
    console.log("111 收到发布的 " + topics[topic] + " 相关的内容: " + contents);
});
user1.ps.subscribe(user1.userid, "Z_Z", function(topic, contents){
    console.log("111 收到发布的 " + topics[topic] + " 相关的内容: " + contents);
});

user1.ps.unsubscribe(user1.userid, "J_S");

var user2 = new User(222, pubsub);
user2.ps.subscribe(user2.userid, "J_S", function(topic, contents){
    console.error("222 收到发布的 " + topics[topic] + " 相关的内容: " + contents);
});

var user3 = new User(333, pubsub);
user3.ps.subscribe(user3.userid, "J_J", function(topic, contents){
    console.log("333 收到发布的 " + topics[topic] + " 相关的内容: " + contents);
});


pubsub.publish("J_S", "中国南海要开战了!!!!!!");
pubsub.publish("J_J", "中国经济危机!!!!!!");
pubsub.publish("Z_Z", "中国高层内斗习李不和!!!!!!");
